package com.wang.system.service.impl;

import com.wang.system.service.IUserService;

import com.github.pagehelper.PageHelper;
import com.wang.common.security.exception.ServiceException;
import com.wang.common.core.enums.ResultCode;
import com.wang.system.domain.user.User;
import com.wang.system.domain.user.dto.UserDTO;
import com.wang.system.domain.user.dto.UserQueryDTO;
import com.wang.system.domain.user.vo.UserVO;
import com.wang.system.manager.UserCacheManager;
import com.wang.system.mapper.UserMapper;
import com.wang.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserCacheManager userCacheManager;

    @Override
    public List<UserVO> list(UserQueryDTO userQueryDTO) {
        PageHelper.startPage(userQueryDTO.getPageNum(),userQueryDTO.getPageSize());
        return userMapper.selectUserList(userQueryDTO);
    }

    @Override
    public int updateStatus(UserDTO userDTO) {
        //1.先根据用户 id 从数据库中查出相应用户.
        //SELECT * FROM user WHERE user_id = #{userId};
        User user = userMapper.selectById(userDTO.getUserId());

        if (user == null){
            throw new ServiceException(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        //2.修改用户状态
        user.setStatus(userDTO.getStatus());

        //3.更新缓存中的用户状态
        userCacheManager.updateStatus(userDTO.getUserId(), userDTO.getStatus());

        //4.更新数据库中的用户状态
        //UPDATE user SET status = #{status} WHERE user_id = #{userId};
        return userMapper.updateById(user);
    }
}
